package com.chii.color.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PassEncode {

    public static void main(String[] args) {
        System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        String password = "chenliji1";
        password = getSHA(password);
        System.out.println(password);//35b592f9bcafd80ebd486b2591ad36d3c101e9b2
        password = new BCryptPasswordEncoder().encode(password);
        System.out.println(password);//$2a$10$OEI/PpE5bkI19o9KajlrPOUTsSFSECvmbllQxZIA1nkzJdd59HYeu
    }


    /**
     * SHA-1加密字符串
     *
     * @param info
     * @return
     */
    public static String getSHA(String info) {
        byte[] bytesSHA = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            // 添加要进行计算摘要的信息
            messageDigest.update(info.getBytes());
            // 得到该摘要
            bytesSHA = messageDigest.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return byteToHex(bytesSHA);
    }

    /**
     * Bytes数组转换为字符串
     *
     * @param bytes
     * @return
     */
    private static String byteToHex(byte[] bytes) {
        StringBuilder hs = new StringBuilder();
        String temp;
        for (byte b : bytes) {
            temp = (Integer.toHexString(b & 0XFF));
            if (temp.length() == 1) {
                hs.append("0").append(temp);
            } else {
                hs.append(temp);
            }
        }
        return hs.toString();
    }
}
